package com.leijingqi.interceptor;

import com.alibaba.fastjson2.JSON;
import com.leijingqi.pojo.Result;
import com.leijingqi.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor  implements HandlerInterceptor {
    @Override  //接口调用前 执行  true false控制放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求地址
        String url = request.getRequestURI().toString();

        //获取token
        String jwt = request.getHeader("token");
        //判断令牌存在
        if(!StringUtils.hasLength(jwt)){ //不存在
            Result error = Result.error("NOT_LOGIN");
            //转换JSON
            String notLogin = JSON.toJSONString(error);
            response.getWriter().write(notLogin);  //响应给客户端
            return false;
        }
        //解析token
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e){
            e.printStackTrace();
            System.out.println("解析失败");
            Result error = Result.error("NOT_LOGIN");
            //转换JSON
            String notLogin = JSON.toJSONString(error);
            response.getWriter().write(notLogin);  //响应给客户端
            return false;
        }
        return true;
    }

    @Override //接口调用后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override  //最后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
